﻿/**
 * Copyright (c) 2012, IceRealm.org - all rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * 
 * Project Page: https://mcts.codeplex.com
 * Contact:      http://www.icerealm.org/contact
 *               icedragon@quickfox.org
 */

using System;
using System.IO;
using System.Windows.Forms;

namespace Minecraft_Text_Splitter
{
    public partial class Form1 : Form
    {
        public const string PROJECT_PAGE_LINK = "https://mcts.codeplex.com";

        /*** MEMBERS *********************************************************/
        private bool ClearText = true;
        private BlockSplitter Splitter = null;

        private bool HasBlockSizeChanged { get { return Splitter == null || (int)blockSize.Value != Splitter.BlockSize; } }
        private bool HasDataLoaded = false;
        private string Status
        {
            get { return textStatus.Text; }
            set { textStatus.Text = value; }
        }


        /*** CONSTRUCTOR *****************************************************/
        public Form1()
        {
            InitializeComponent();
            //textInput.Select(0, 0);
        }


        /*** HELPER FUNCTIONS ************************************************/
        private void loadTextFile(string fileName)
        {
            textInput_Enter(null, null);
            try
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    textInput.Text = sr.ReadToEnd();
                    HasDataLoaded = false;
                    Status = "Click Next";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool prepareData()
        {
            textInput.Text = textInput.Text.Trim();

            if (Splitter == null)
                Splitter = new BlockSplitter((int)blockSize.Value);

            if (textInput.Text.Length == 0)
            {
                MessageBox.Show("No text", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (HasBlockSizeChanged)
            {
                HasDataLoaded = false;
                Splitter.ChangeBlockSize((int)blockSize.Value, false);
            }

            if (!HasDataLoaded)
            {
                try
                {
                    Splitter.ProcessText(textInput.Text);
                    HasDataLoaded = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }

            return true;
        }

        private void selectBlock(int start, int end)
        {
            textInput.Focus();
            textInput.Select(start, end - start);
            textInput.ScrollToCaret();
        }

        private void processText(string text)
        {
            textClipboard.Text = text;
            Clipboard.SetText(textClipboard.Text);
            selectBlock(Splitter.CurrentStartOffset, Splitter.CurrentEndOffset);
            Status = String.Format("Page: {0}/{1}", Splitter.CurrentBlock + 1, Splitter.TotalBlocks);

            if (textClipboard.Text.Length > Splitter.BlockSize)
                MessageBox.Show(String.Format("Clipboard text is longer than block size by {0} byte(s)! Notify me (icedragon@quickfox.org)", textClipboard.Text.Length - Splitter.BlockSize), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void enableNavButtons(object sender = null, EventArgs e = null)
        {
            btnNext.Enabled = true;
            btnPrev.Enabled = true;
        }

        private void disableNavButtons()
        {
            btnNext.Enabled = false;
            btnPrev.Enabled = false;
        }


        /*** EVENTS **********************************************************/
        private void btnLoad_Click(object sender, EventArgs e)
        {
            if (loadDialog.ShowDialog() == DialogResult.OK)
                loadTextFile(loadDialog.FileName);
        }

        private void textInput_Enter(object sender, EventArgs e)
        {
            // Clear the introduction text
            if (ClearText)
            {
                ClearText = false;
                textInput.Text = "";
            }
        }

        private void textInput_TextChanged(object sender, EventArgs e)
        {
            if (textInput.Text.Trim().Length > 0)
            {
                Status = "Click Next";
                enableNavButtons();
            }
            else
            {
                Status = "No text";
                disableNavButtons();
            }

            HasDataLoaded = false;
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (prepareData())
                processText(Splitter.NextBlock);
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (prepareData())
                processText(Splitter.PrevBlock);
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop)
                 ? DragDropEffects.Copy
                 : DragDropEffects.None;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                loadTextFile(files[0]);

                if (files.Length > 1)
                    MessageBox.Show(String.Format("Only the first file ({0}) was loaded", files[0]), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void lnkProjectPage_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.ProcessStartInfo sInfo = new System.Diagnostics.ProcessStartInfo(PROJECT_PAGE_LINK);
            System.Diagnostics.Process.Start(sInfo);
        }
    }
}
